package com.liy.framework.common.orm.dialect;

public class OracleDialect extends Dialect {

    public String getQueryDataString(String sql, int offset, int limit) {
        sql = sql.trim();
        boolean isForUpdate = false;
        if (sql.toLowerCase().endsWith(" for update")) {
            sql = sql.substring(0, sql.length() - 11);
            isForUpdate = true;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT * FROM  ");
        sb.append(" (");
        sb.append(" SELECT A.*, ROWNUM RN  ");
        sb.append(" FROM (");
        sb.append(sql);
        sb.append(") A ");
        sb.append(" WHERE ROWNUM < " + (offset + limit));
        sb.append(" )");
        sb.append(" WHERE RN >= " + offset);
        if (isForUpdate) {
            sb.append(" for update");
        }

        return sb.toString();
    }

    public String getQueryCountString(String sql) {
        StringBuffer buffer = new StringBuffer(sql.length() + 30);
        buffer.append("select count(1) from (").append(sql).append(")");
        return buffer.toString();
    }
}
